
/**
 * 核心模块
 */
define(["jquery","jquery.cookie","bootstrap","bootstrap.paginator"],function($)
{
	var core={};
	
	//系统
	core.System=
	{
		APP_NAME:"", //程序名
		HOST:"", //地址
		PATH:"", //全路径
		ROOT_PATH:"", //根路径
		STATIC_PATH:"", //静态文件路径
		API_PATH:"", //api地址
		INCLUDE_PATH:"", //引用页路径
		MANAGE_PATH:"/manage", //后台管理页路径
		MANAGE_INDEX:"/index", //后台管理首页
		MANAGE_INCLUDE_PATH:"/include/manage", //后台管理引用页
		init:function()
		{
			core.System.PATH=core.System.HOST+core.System.ROOT_PATH;
			core.System.API_PATH=core.System.PATH+core.System.API_PATH;
			core.System.MANAGE_PATH=core.System.PATH+core.System.MANAGE_PATH;
			core.System.MANAGE_INDEX=core.System.MANAGE_PATH+core.System.MANAGE_INDEX;
			core.System.MANAGE_INCLUDE_PATH=core.System.PATH+core.System.MANAGE_INCLUDE_PATH;
		}
	};
	
	//api
	core.api=
	{
		getApi:function(path)
		{
			return core.System.API_PATH+path;
		}
	};
	
	//常量
	core.constants=
	{
		LOGIN_TOKEN_COOKIE:"osc_token",
		//登录令牌过期时间   1小时
		LOGIN_TOKEN_TIMEOUT:1000*60*60*24*30
	};
	
	//广播
	core.broadcasts=
	{
		COMMENT_BEFORE:"COMMENT_BEFORE",
		COMMENT_AFTER:"COMMENT_AFTER",
		USER_MESSAGE_CARD_BEFORE:"USER_MESSAGE_CARD_BEFORE",
		USER_MESSAGE_CARD_AFTER:"USER_MESSAGE_CARD_AFTER",
		BLOG_CATALOG_INCLUDE_BEFORE:"BLOG_CATALOG_INCLUDE_BEFORE",
		BLOG_CATALOG_INCLUDE_AFTER:"BLOG_CATALOG_INCLUDE_AFTER"
	};
	
	//令牌
	core.token=
	{
		get:function()
		{
			return core.util.cookie.get(core.constants.LOGIN_TOKEN_COOKIE);
		},
		set:function(token)
		{
			core.util.cookie.set(core.constants.LOGIN_TOKEN_COOKIE,token,core.constants.LOGIN_TOKEN_TIME);
		},
		remove:function()
		{
			core.util.cookie.remove(core.constants.LOGIN_TOKEN_COOKIE);
		}
	};
	
	//信息
	core.message=
	{
		//解析结果
		parseResult:function(result)
		{
			if(core.util.isBlank(result))
				return {success:false,message:core.message.message.ERROR_DATA_ERROR};
			
			if(!core.util.isObject(result))
				result=core.util.toJSON(result);
			
			result.message=core.message.getMessage(result.message);
			return result;
		},
		//获得信息字符串
		getMessage:function(value)
		{
			var parseStr=function(value)
			{
				try
				{
					return eval("core.message.message."+value);	
				}
				catch(e)
				{
					return "";
				}
			};
			
			var parseObj=function(value)
			{
				try
				{
					return core.util.toJSON(value);
				}
				catch(e)
				{
					return null;
				}
			};
			
			var parseArg=function(value,args)
			{
				for(var i=0;i<args.length;i++)
				{
					value=core.util.replace(value,"<"+i+">",args[i]);
				}
				return value;
			};
			
			var newValue=parseStr(value);
			if(core.util.isBlank(newValue))
			{
				var valueObj=parseObj(value);
				
				if(core.util.isBlank(valueObj))
					return value;
				
				return parseArg(parseStr(valueObj.message),valueObj.args);
			}
			else
				return newValue;
		},
		message:
		{
			UNLAWFUL_OPERATION:"非法操作",
			DATA_NOT_FOUND:"暂无数据",
			ERROR_DATA_ERROR:"数据错误",
			ERROR_UNAUTHORIZED:"权限不足,请先登录或联系管理员",
			ERROR_APP_ERROR:"程序错误",
			CREATE_SUCCESS:"创建成功",
			UPDATE_SUCCESS:"更新成功",
			UPDATE_SUCCESS_DELAY:"更新成功,可能会有延迟",
			CREATE_SUCCESS_DELAY:"创建成功,可能会有延迟",
			DELETE_SUCCESS_DELAY:"删除成功,可能会有延迟",
			DELETE_SUCCESS:"删除成功",
			UPLOAD_ERROR_TYPE_ERROR:"上传失败:类型错误,只允许 <0> 类型",
			UPLOAD_ERROR_OUT_OF_SIZE:"上传失败:尺寸过大,不能超过 <0> MB",
			CHECK_SUCCESS:"审核成功",
			REGISTER_SUCCESS:"注册成功",
			REGISTER_ERROR_USER_IS_EXIST:"用户已存在",
			LOGIN_SUCCESS:"登录成功",
			LOGIN_ERROR_USER_NOT_FOUND:"用户不存在",
			LOGIN_ERROR_PASSWORD_ERROR:"密码错误",
			LOGIN_ERROR_USER_IS_ONLINE:"用户已在线",
			LOGOUT_SUCCESS:"登出成功",
			LOGOUT_FAILURE:"登出失败",
			DONGTAN_CREATE_SUCCESS:"动弹发表成功",
			COMMENT_CREATE_SUCCESS:"评论发表成功",
			ROLE_UPDATE_SUCCESS:"角色更新成功",
			SOFTWARE_ERROR_IS_EXIST:"软件已存在",
			SOFTWARE_CREATE_SUCCESS:"软件添加成功,已提交审核",
			DISCUSS_CREATE_SUCCESS:"发表成功",
			USER_FOLLOW_CREATE_SUCCESS:"关注成功",
			USER_FOLLOW_CREATE_FAILURE_IS_EXIST:"已经关注过",
			USER_FOLLOW_DELETE_SUCCESS:"取消关注成功",
			USER_FOLLOW_CREATE_FAILURE_ONESELF:"不能关注自己",
			BLOG_CREATE_SUCCESS:"发表成功",
			USER_EDIT_USERNAME_IS_EXIST:"用户名已存在",
			USER_MAIL_CREATE_FAILURE_NOT_YOURSELF:"不能给自己发送",
			USER_MAIL_CREATE_FAILURE_TARGET_NOT_FOUND:"用户不存在",
			MAIL_CREATE_SUCCESS:"发送成功",
			FAVORITE_CREATE_SUCCESS:"关注成功",
			FAVORITE_CREATE_FAILURE_IS_FAVORITE:"已经关注过",
			FAVORITE_DELETE_SUCCESS:"取消成功",
			REPORT_CREATE_SUCCESS:"举报成功",
			OPERATION_SUCCESS:"操作成功",
			USER_UPDATE_PASSWORD_FAILURE_SOURCE_PASSWORD_ERROR:"原密码错误",
			REGISTER_FAILURE_IS_CHECK:"注册成功,验证邮件已发送到 <0>",
			REGISTER_CHECK_SUCCESS:"用户 '<0>' 认证成功"
		}
	};
	
	core.parser=
	{
		//解析html
		html:function(source)
		{
			var oldStr=["&quot;","&apos;","&lt;","&gt;", "<n>", "<t>", "<n>"];
			var newStr=["\"", "'", "<", ">", "\n", "\t", "\r"];
			for(var i=0;i<oldStr.length;i++)
				source=core.util.replace(source,oldStr[i],newStr[i]);
			return source;
		}		
	};
	
	//dom操作
	core.dom=
	{
		//是否是最顶端
		isTop:function()
		{
			return !($(document).scrollTop()>0);
		},
		//是否是最底端
		isBottom:function()
		{
			var st=$(document).scrollTop(),winh=$(window).height();
			return (st>=$(document).height()-winh);
		}
	};
	
	//工具
	core.util=
	{
		//是否为整数类型
		isInteger:function(value)
		{
			if(core.util.isBlank(value))
				return false;
			
			return !isNaN(parseInt(value));
		},
		//返回对象原型
		getObjectSource:function(obj)
		{
			return Object.prototype.toString.call(obj);
		},
		//是否为数组
		isArray:function(obj)
		{
			return core.util.getObjectSource(obj)==="[object Array]";
		},
		//是否为对象
		isObject:function(obj)
		{
			return core.util.getObjectSource(obj)==="[object Object]";
		},
		//刷新
		refresh:function()
		{
			window.location.reload();
		},
		//替换
		replace:function(value,oldStr,newStr)
		{
			if(core.util.isBlank(value))
				return "";
			
			var reg=new RegExp(oldStr,"gi");
			return value.replace(reg,newStr);
		},
		//克隆对象
		clone:function(myObj)
		{
			if(typeof(myObj)!='object')
				return myObj;
			if(myObj==null)
				return myObj;

			var myNewObj=new Object();

			for (var i in myObj)
				myNewObj[i]=core.util.clone(myObj[i]);

			return myNewObj;
		},
		//把obj1的属性复制到obj2  返回复制的属性数量
		copyAttribute:function(obj1,obj2)
		{
			var count=0;
			for(var i in obj1)
			{
				obj2[i]=obj1[i];
				count++;
			}

			return count;
		},
		/**
		 * 是否支持html5 支持返回true
		 */
		checkHTML5:function()
		{
			return typeof(Worker)!=="undefined";
		},
		/**
		 * 获得URL参数
		 */
		getQueryString:function(name)
		{
			var reg=new RegExp("(^|&|#|/?)"+name+"=([^&]*)(&|$)","i");
		    var r=window.location.toString().match(reg);
		    if (r != null)
		    	return unescape(r[2]);
		    return null;
		},
		/**
		 * 判断是否是IE  如果是返回true
		 */
		isIE:function()
		{
			return (!window.addEventListener);
		},
		refreshPage:function()
		{
			setTimeout(function()
			{
				window.location.reload();
			},1);
		},
		/**
		 * 转UTF8
		 */
		toUTF8:function(gbk)
		{
		    if(!gbk)
		    	return '';
		    var utf8=[];
		    for(var i=0;i<gbk.length;i++)
		    {
		        var s_str=gbk.charAt(i);
		        if(!(/^%u/i.test(escape(s_str))))
		        {
		        	utf8.push(s_str);
		        	continue;
		        }
		        var s_char=gbk.charCodeAt(i);
		        var b_char=s_char.toString(2).split('');
		        var c_char=(b_char.length==15)?[0].concat(b_char):b_char;
		        var a_b=[];
		        a_b[0]='1110'+c_char.splice(0,4).join('');
		        a_b[1]='10'+c_char.splice(0,6).join('');
		        a_b[2]='10'+c_char.splice(0,6).join('');
		        for(var n=0;n<a_b.length;n++)
		            utf8.push('%'+parseInt(a_b[n],2).toString(16).toUpperCase());
		    }
		    return utf8.join('');
		},
		/**
		 * 是否为空
		 */
		isBlank:function(str)
		{
			if(str==undefined || str==null || str=="")
				return true;
			return false;
		},
		/**
		 * 简单post请求
		 */
		simplePost:function(url,property,callback)
		{
			$.post(url,property,function(data)
			{
				if(core.util.isBlank(data))
					data=null;
				callback(data);
			});
		},
		/**
		 * 简单get请求
		 */
		simpleGet:function(url,property,callback)
		{
			$.get(url,property,function(data)
			{
				if(core.util.isBlank(data))
					data=null;
				callback(data);
			});
		},
		/**
		 * 转为json
		 */
		toJSON:function(str)
		{
			if(!core.util.isBlank(str))
				return JSON.parse(str);
			else
				return {};
		},
		/**
		 * 默认值
		 */
		defaultValue:function(source,_default)
		{
			if(core.util.isBlank(source))
				return _default;
			return source;
		},
		/**
		 * 加载CSS文件
		 */
		loadCssFile:function(file,callback)
		{
			callback=core.util.defaultValue(callback,function(){});
		    var link=document.createElement("link");
		    link.type="text/css";
		    if(link.readyState)
		    {
		        link.onreadystatechange=function()
		        {
		            if(link.readyState=="loaded" || link.readyState=="complete")
		            {
		                link.onreadystatechange=null;
		                callback();
		            }
		        };
		    }
		    else
		    {
		        link.onload=function()
		        {
		            callback();
		        };
		    }
		    link.href=file;
		    link.rel="stylesheet";
		    document.getElementsByTagName("head")[0].appendChild(link);
		},
		trim:function(str)
		{
			if(core.util.isBlank(str))
				return "";
			
			str=String(str);
			return str.replace(/\r\n\t/ig,'').replace(/^[\s]+/,'').replace(/[\s]+$/,'').replace(/[\s]{2,}/,' ');
		},
		cookie:
		{
			// 设置Cookie
			set:function(name,value,time)
			{
				$.cookie(name, value, {expires: time, path: "/"});
			},
			// 根据名称返回cookie
			get:function(name)
			{
				return $.cookie(name);
			},
			//移除
			remove:function(name)
			{
				core.util.cookie.set(name,"",0);
			}
		},
		//地址变化事件
		onLocationChange:function()
		{
			var callbacks=[];
			var oldLocation=location.href;
			
			setInterval(function()
			{
				var newLoaction=location.href;
				if(oldLocation!=newLoaction)
				{
					for(var i=0;i<callbacks.length;i++)
					{
						callbacks[i].callback(oldLocation,newLoaction);
						if(callbacks[i].clean)
							callbacks.splice(i,1);
					}
					oldLocation=newLoaction;
				}
			},500);
			
			/**
			 * @param callback 回调
			 * @param clean 是否每次地址变更清除这个回调
			 */
			return function(callback,clean)
			{
				if(core.util.isBlank(clean))
					clean=true;
				
				callbacks.push({callback:callback,clean:clean});
			};
		}(),
		//锁
		Lock:function()
		{
			var lock=false;
		
			var _call=function(func)
			{
				if(lock==true)
					return;
					
				lock=true;
				func();
				lock=false;
			};
			
			this.call=function(func)
			{
				_call(func);
			}
		}
	};
	
	//ui
	core.ui=
	{
		//简单弹出层
		simpleDialog:function(message,func)
		{
			func=core.util.defaultValue(func,function(){});
			var dialog=core.ui.dialog
			({
				title:"提示",
				content:message,
				buttons:
				[
					{
						name:"确认",
						_class:"default",
						func:function()
						{
							dialog.close();
						}
					}
				],
				onClose:function()
				{
					func();
				}
			});
			return dialog;
		},
		//简单弹出层  带取消按钮和事件绑定
		simpleDialogEx:function(message,check,cancel)
		{
			check=core.util.defaultValue(check,function(){});
			cancel=core.util.defaultValue(cancel,function(){});
			var dialog=core.ui.dialog
			({
				title:"提示",
				content:message,
				buttons:
				[
					{
						name:"<i class='glyphicon glyphicon-ok-circle'></i> 确认",
						_class:"success",
						func:function()
						{
							dialog.close();
							check();
						}
					},
					{
						name:"<i class='glyphicon glyphicon-remove-circle'></i> 取消",
						_class:"danger",
						func:function()
						{
							dialog.close();
							cancel();
						}
					}
				]
			});
			return dialog;
		},
		//弹出层
		dialog:function(option)
		{
			var dialogDefaultOption=
			{
				title:"",
				content:"",
				modal:"static", //是否显示遮罩层 static代表点击遮罩层不关闭弹出层
				showClose:true, //是否显示关闭按钮
				resizable:false,
				buttons:[],
				width:0,
				height:0,
				onOpen:function(){},
				onClose:function(){}
			};
			option=$.extend([],dialogDefaultOption,option);
			if(core.util.isBlank(option.content))
				return;
			
			var dialog=(function()
			{
				var $dialog=$('<div class="modal fade" role="dialog" aria-hidden="true"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title"></h4></div> <div class="modal-body"></div><div class="modal-footer"><div type="button-group"></div></div> </div></div></div>');
				var modalContent=$dialog.find(".modal-content");
				var modalFooter=$dialog.find(".modal-footer");
				
				var event=
				{
					open:function(){},
					close:function(){}
				};
				
				return {
					getInstance:function()
					{
						return $dialog;	
					},
					setTitle:function(title)
					{
						$dialog.find(".modal-title").html(title);
					},
					setContent:function(content)
					{
						$dialog.find(".modal-body").html(content);
					},
					setHeight:function(height)
					{
						modalContent.height(height);
					},
					setWidth:function(width)
					{
						modalContent.width(width);
					},
					setButton:function(buttons)
					{
						var buttonGroup=$dialog.find("[type='button-group']");
						for(var i=0;i<buttons.length;i++)
						{
							var temp=$('<button type="button" class="btn btn-'+buttons[i]._class+' btn-sm" button_index="'+i+'">'+buttons[i].name+'</button>');
							buttonGroup.append(temp);
							temp.click(function()
							{
								buttons[$(this).attr("button_index")].func();
							});
						}
					},
					removeButton:function()
					{
						$dialog.find(".modal-footer").remove();
						//$dialog.find("[type='button-group']").remove();
					},
					hideClose:function()
					{
						$dialog.find(".close").hide();
					},
					show:function(backdrop)
					{
						$dialog.modal
						({
							backdrop:backdrop
						});
						
						$dialog.on('shown.bs.modal',function(e)
						{
							event.open();
						});
					
						$dialog.on('hidden.bs.modal',function(e)
						{
							event.close();
							$dialog.remove();
						});
					},
					close:function()
					{
						$dialog.modal("hide");
					},
					onOpen:function(callback)
					{
						event.open=callback;
					},
					onClose:function(callback)
					{
						event.close=callback;
					}
				}
			}());
			
			dialog.setContent(option.content);
			dialog.setTitle(option.title);
			
			if(option.height!=0)
				dialog.setHeight(option.height);
			
			if(option.width!=0)
				dialog.setWidth(option.width);
			
			if(option.buttons.length>0)
				dialog.setButton(option.buttons);
			else
				dialog.removeButton();
			
			if(!option.showClose)
				dialog.hideClose();
			
			dialog.onOpen(function()
			{
				option.onOpen();
			});
			
			dialog.onClose(function()
			{
				option.onClose();
			});
			
			dialog.show();
			return dialog;
		},
		/**
	 	* 分页
	 	*/
		paginate:function(option)
		{
			var paginateDefaultOption=
			{
				element:null, //覆盖到
				url:"", //链接 会拼一个pn
				pageCount:0, // 每页数量
				dataSum:0, //数据总数
				start:1, //开始
				showCount:5, //只显示多少个
				onlyOneShow:false //如果只有一页不显示
			};
	
			option=$.extend([],paginateDefaultOption,option);
			
			if(core.util.isBlank(option.element))
				return;	
			
			if(option.dataSum==0)
				return;
			
			option.start=parseInt(option.start);
			if(option.dataSum>option.pageCount)
				option.count=parseInt(option.dataSum%option.pageCount!=0?option.dataSum/option.pageCount+1:option.dataSum/option.pageCount);
			else
				option.count=1;
			
			if(option.onlyOneShow && option.count==1)
				return;
			
			if(core.util.isBlank(option.click) && !core.util.isBlank(option.url))
			{
				option.click=function(url,page)
				{
					window.location.href="#"+url+page;
				}
			}
			var options=
			{
				size:"small",
				bootstrapMajorVersion:3,
	            currentPage:option.start,
	            totalPages:option.count,
	            numberOfPages:option.showCount,
	            useBootstrapTooltip:true,
	            itemTexts: function (type, page, current)
	            {
                    switch (type)
                    {
	                    case "first":
	                        return "<<";
	                    case "prev":
	                        return "<";
	                    case "next":
	                        return ">";
	                    case "last":
	                        return ">>";
	                    case "page":
	                        return page;
                    }
                },
                tooltipTitles: function (type, page, current)
                {
                    switch (type)
                    {
	                    case "first":
	                        return "首页";
	                    case "prev":
	                        return "上一页";
	                    case "next":
	                        return "下一页";
	                    case "last":
	                        return "尾页";
	                    case "page":
	                        return "第"+page+"页";
                    }
                },
                onPageClicked:function(e,originalEvent,type,page)
                {
                	option.click(page);
                },
                pageUrl: function(type, page, current)
                {
                	if(core.util.isBlank(option.url))
                		return null;
                	return option.url+page;
           	 	}
	        }
	        
	        var $ul=$("<ul></ul>");
	       	$ul.bootstrapPaginator(options);
	        option.element.html($ul);
	        return true;
		}
	};
	
	// 对Date的扩展，将 Date 转化为指定格式的String
	// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
	// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
	// 例子：
	// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
	// (new Date()).Format("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
	Date.prototype.format = function(fmt)
	{
		var o=
		{
			"M+" : this.getMonth() + 1, // 月份
			"d+" : this.getDate(), // 日
			"h+" : this.getHours(), // 小时
			"m+" : this.getMinutes(), // 分
			"s+" : this.getSeconds(), // 秒
			"q+" : Math.floor((this.getMonth() + 3) / 3), // 季度
			"S" : this.getMilliseconds()
			// 毫秒
		};
		if (fmt == undefined || fmt == null || fmt == "")
			fmt = "yyyy-MM-dd hh:mm:ss";
		if (/(y+)/.test(fmt))
			fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "")
							.substr(4 - RegExp.$1.length));
		for (var k in o)
			if (new RegExp("(" + k + ")").test(fmt))
				fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1)
								? (o[k])
								: (("00" + o[k])
										.substr(("" + o[k]).length)));
		return fmt;
	}

	return core;
});